package com.itheima.ydd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.dto.MenuDto;
import com.itheima.ydd.entity.Menu;
import com.itheima.ydd.mapper.MenuMapper;
import com.itheima.ydd.service.MenuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author yan.zhou
 * @since 2022-02-22
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> menuList(String role_id) {
        String[] strings = role_id.split(",");
        List<Menu> menuList = menuMapper.findMenuList(strings);
        return menuList;
    }

    @Override
    public void removeIfNoChild(Integer id) {

        // 先判断有没有以此菜单为父级的菜单
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Menu::getPid, id);
        if (super.count(queryWrapper) > 0) {
            // 有则抛出异常
            throw new BusinessException("存在子级，不允许删除！");
        }
        // 无则删除
        super.removeById(id);
    }

    @Override
    public void childList(MenuDto menuDto) {

        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Menu::getPid, menuDto.getId());
        List<Menu> menuList = super.list(queryWrapper);
        if (menuList.isEmpty()) {
            return;
        }
        List<MenuDto> menuDtoList = menuList.stream().map(menu -> {
            MenuDto childMenuDto = new MenuDto();
            BeanUtils.copyProperties(menu, childMenuDto);
            childList(childMenuDto);
            return childMenuDto;
        }).collect(Collectors.toList());
        menuDto.setChildren(menuDtoList);
    }

}
